<template>
    <div class="container">
        <!-- 顶部导航栏 -->
        <HeaderNav :active-menu="activeMenu" @menu-select="handleMenuSelect" @user-command="handleUserCommand" />

        <!-- 主内容区域 -->
        <div class="main-content">

            <!-- 右侧内容区域 -->
            <main class="content">
                <div class="content-wrapper">
                    <!-- 返回按钮 -->
                    <el-button type="text" icon="el-icon-back" @click="$router.back()" class="back-btn">
                        返回列表
                    </el-button>

                    <!-- 职位详情卡片 -->
                    <el-card class="job-detail-card">
                        <!-- 职位头部信息（仅保留模型中存在的字段） -->
                        <div class="job-header">
                            <div class="job-main-info">
                                <h1 class="job-title" v-if="jobDetail">{{ jobDetail.title }}</h1>
                                <div class="job-basic" v-if="jobDetail">
                                    <span class="salary">{{ jobDetail.salary_range }}</span>
                                    <span class="separator">|</span>
                                    <span>{{ jobDetail.location }}</span>
                                </div>
                            </div>

                            <div class="job-actions">
                                <el-button type="primary" size="medium" @click="applyJob(jobDetail.job_id)"
                                    v-if="userStore.isLoggedIn()">
                                    立即申请
                                </el-button>
                            </div>
                        </div>

                        <!-- 公司信息（仅显示模型中的company字段） -->
                        <div class="company-info">
                            <div class="company-details" v-if="jobDetail">
                                <h2>{{ jobDetail.company }}</h2>
                            </div>
                        </div>

                        <!-- 职位详情内容（仅使用模型中的description和requirements） -->
                        <!-- 修改后：先判断jobDetail存在 -->
                        <div class="content-section" v-if="jobDetail"> <!-- 关键：添加v-if判断 -->
                            <h3 class="section-title">职位描述</h3>
                            <div class="section-content">
                                <p v-for="(paragraph, index) in jobDetail.description.split('\n')" :key="index">
                                    {{ paragraph }}
                                </p>
                            </div>
                        </div>

                        <!-- 处理任职要求（依赖requirements） -->
                        <div class="content-section" v-if="jobDetail">
                            <h3 class="section-title">任职要求</h3>
                            <div class="section-content">
                                <ul>
                                    <li v-for="(req, index) in jobDetail.requirements.split('\n')" :key="index">
                                        {{ req }}
                                    </li>
                                </ul>
                            </div>
                        </div>
                        <!-- 申请信息（仅使用模型中的created_at和expires_at） -->
                        <div class="application-info" v-if="jobDetail">
                            <el-divider content-position="left">申请信息</el-divider>
                            <p>发布时间：{{ formatTime(jobDetail.created_at) }}</p>
                            <p>截止日期：{{ formatDate(jobDetail.expires_at) }}</p>
                        </div>
                    </el-card>

                    <!-- 底部操作按钮 -->
                    <div class="bottom-actions" v-if="jobDetail">
                        <el-button type="primary" size="medium" @click="applyJob(jobDetail.job_id)"
                            v-if="userStore.isLoggedIn()">
                            立即申请
                        </el-button>
                        <el-button type="default" size="medium" @click="$router.back()">
                            返回列表
                        </el-button>
                    </div>
                </div>
            </main>
        </div>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElDivider, ElButton, ElAvatar } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 导入组件
import HeaderNav from '@/components/layout/HeaderNav.vue'

// 路由和状态管理
const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

// 响应式数据（仅关联模型字段）
const activeMenu = ref('recruitment')
const activeSidebar = ref('jobs')
const jobDetail = ref(null) // 存储职位详情，字段与模型一致

// 格式化时间（复用列表页逻辑）
const formatTime = (timeString) => {
    const date = new Date(timeString)
    const now = new Date()
    const diffInSeconds = Math.floor((now - date) / 1000)

    if (diffInSeconds < 60) return `${diffInSeconds}秒前`
    if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}分钟前`
    if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}小时前`
    return `${Math.floor(diffInSeconds / 86400)}天前`
}

// 格式化日期（复用列表页逻辑）
const formatDate = (timeString) => {
    const date = new Date(timeString)
    return date.toLocaleDateString()
}

// 获取职位详情（仅请求模型中存在的字段）
const fetchJobDetail = async () => {
    const jobId = route.params.jobId;
    jobDetail.value = null; // 开始请求前重置为null，避免旧数据干扰
    try {
        const response = await axios.get(`/api/jobs/${jobId}`);
        if (response.data.code === 0 && response.data.data) {
            jobDetail.value = response.data.data; // 成功：赋值有效数据
        } else {
            ElMessage.error('获取职位详情失败：' + (response.data.msg || '数据异常'));
            jobDetail.value = null; // 失败：明确为null
        }
    } catch (error) {
        ElMessage.error('获取职位详情失败：接口请求错误');
        jobDetail.value = null; // 异常：明确为null
    }
};

// 申请职位（复用列表页逻辑）
const applyJob = async (jobId) => {
    try {
        // 获取当前用户简历
        const resumesResponse = await axios.get('/api/resumes/my', {
            headers: { token: localStorage.getItem('token') }
        })

        if (resumesResponse.data.code === 0 && resumesResponse.data.data.list.length === 0) {
            ElMessage.warning('请先创建简历再申请职位')
            return router.push('/resumes/create')
        }

        // 投递第一个简历
        const resumeId = resumesResponse.data.data.list[0].resume_id
        const response = await axios.post(`/api/jobs/${jobId}/apply`,
            { resume_id: resumeId },
            { headers: { token: localStorage.getItem('token') } }
        )

        if (response.data.code === 0) {
            ElMessage.success('申请成功，等待雇主回复')
        } else {
            ElMessage.error(response.data.msg || '申请失败')
        }
    } catch (error) {
        ElMessage.error('操作失败，请稍后重试')
        console.error(error)
    }
}

// 导航处理（与列表页一致）
const handleMenuSelect = (index) => {
    activeMenu.value = index
    router.push({ name: index.charAt(0).toUpperCase() + index.slice(1) })
}

const handleSidebarSelect = (index) => {
    activeSidebar.value = index
    if (index === 'chat') router.push('/chat')
    else ElMessage.info(`导航到: ${index}`)
}

const handleUserCommand = async (command) => {
    switch (command) {
        case 'profile': router.push('/profile'); break
        case 'logout':
            localStorage.removeItem('token')
            localStorage.removeItem('userInfo')
            ElMessage.success('已退出登录')
            router.push('/login')
            break
        default: ElMessage.info(`执行命令: ${command}`)
    }
}

// 页面加载时获取数据
onMounted(() => {
    fetchJobDetail()
})
</script>

<style scoped>
/* 样式保留与列表页一致的风格，仅调整必要部分 */
.container {
    height: 100vh;
    display: flex;
    flex-direction: column;
    background-color: #f5f7fa;
}

.main-content {
    display: flex;
    flex: 1;
    overflow: hidden;
}

.content {
    flex: 1;
    padding: 24px;
    overflow-y: auto;
}

.content-wrapper {
    max-width: 1200px;
    margin: 0 auto;
}

.back-btn {
    margin-bottom: 16px;
}

.job-detail-card {
    padding: 24px;
    margin-bottom: 24px;
}

.job-header {
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin-bottom: 32px;
    flex-wrap: wrap;
    gap: 16px;
}

.job-title {
    font-size: 24px;
    margin-bottom: 16px;
    color: #333;
}

.job-basic {
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    gap: 12px;
    color: #666;
    font-size: 14px;
}

.salary {
    color: #f56c6c;
    font-size: 18px;
    font-weight: bold;
}

.separator {
    color: #ddd;
}

.job-actions {
    display: flex;
    gap: 12px;
}

.company-info {
    display: flex;
    gap: 20px;
    padding: 24px 0;
    border-top: 1px solid #eee;
    border-bottom: 1px solid #eee;
    margin-bottom: 24px;
}

.company-logo {
    flex-shrink: 0;
}

.company-details h2 {
    font-size: 18px;
    margin-bottom: 8px;
}

.content-section {
    margin-bottom: 32px;
}

.section-title {
    font-size: 18px;
    color: #333;
    margin-bottom: 16px;
    padding-left: 8px;
    border-left: 4px solid #409eff;
}

.section-content {
    color: #666;
    line-height: 1.8;
}

.section-content p {
    margin-bottom: 12px;
}

.section-content ul {
    padding-left: 20px;
}

.section-content li {
    margin-bottom: 8px;
}

.application-info {
    color: #666;
    line-height: 2;
}

.bottom-actions {
    display: flex;
    gap: 16px;
    justify-content: center;
    margin: 24px 0;
}

@media (max-width: 768px) {
    .job-header {
        flex-direction: column;
        align-items: flex-start;
    }

    .company-info {
        flex-direction: column;
    }
}
</style>